﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using BastInfos.Models.Visit;
using DataAccess;
using DataAccess.Helpers;
using System.Web.Security;

namespace BastInfos.Controllers
{
	public class VisitController : Controller
	{
		public ActionResult Index()
		{
			var model = new TweetModel();

			model.Tweets = DataRepository.Get<Tweet>()
				.Where(t => t.Validation == (byte)ValidationType.Valide)
				.OrderByDescending(t => t.CreationDate);

            if (Request["display"] != "all")
                model.Tweets.Take(20);
            else if (model.Tweets.Count() > 20)
                model.RestCount = model.Tweets.Count() - 20;

			return View(model);
		}

		[HttpPost]
		public ActionResult Index(Tweet model)
		{
			if (ModelState.IsValid)
			{
				DoAddTweet(model);
			}
			return Index();
		}

		[HttpPost]
		public ActionResult AddTweet(Tweet model)
		{
			if (ModelState.IsValid)
			{
				DoAddTweet(model);
				ViewBag.Added = "added";
				return PartialView("_Tweet", model);
			}
			return new JsonResult { Data = new { error = true} };
		}

		public ActionResult Delete(int id)
		{
			Tweet tweet = DataRepository.Get<Tweet>().FirstOrDefault(t => t.id_Tweet == id);
			if (tweet != null)
			{
				tweet.Validation = (byte)ValidationType.Rejete;
				DataRepository.Context.SubmitChanges();
			}
			return RedirectToAction("Index");
		}

		private void DoAddTweet(Tweet tweet)
		{
			tweet.CreationDate = DateTime.Now;
			tweet.IsBastInfo = User.Identity.IsAuthenticated;

			//!\\ ICI MODIFICATION VALIDATION PAR DEFAUT TWEET
			tweet.Validation = (byte)ValidationType.Valide;

			DataRepository.Get<Tweet>().InsertOnSubmit(tweet);
			DataRepository.Context.SubmitChanges();
		}
	}
}